package udp_tcp.controller;


import udp_tcp.model.Message;
import udp_tcp.model.User;
import udp_tcp.view.ChatFrame;
import udp_tcp.view.LoginDialog;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;

public class ChatController {
    private NetworkController networkController;
    private ChatFrame chatFrame;
    private LoginDialog loginDialog;
    private User currentUser;

    public ChatController() {
        networkController = new NetworkController();
        initializeUI();
    }

    private void initializeUI() {
        loginDialog = new LoginDialog(null);
        loginDialog.setConfirmAction(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleLogin();
            }
        });
        loginDialog.setVisible(true);
    }

    private void handleLogin() {
        String username = loginDialog.getUsername();
        int port = loginDialog.getPort();

        if (username.isEmpty()) {
            JOptionPane.showMessageDialog(loginDialog, "请输入用户名", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (port < 1024 || port > 65535) {
            JOptionPane.showMessageDialog(loginDialog, "端口号必须在1024-65535之间", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        currentUser = new User(username, "localhost");

        try {
            networkController.startServer(port, currentUser);
            showChatWindow();
            loginDialog.dispose();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(loginDialog, "无法启动服务器: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showChatWindow() {
        chatFrame = new ChatFrame("局域网聊天 - " + currentUser.getUsername());
        chatFrame.setSendAction(new AbstractAction("发送") {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = chatFrame.getMessage();
                if (!message.isEmpty()) {
                    networkController.sendMessage(message);
                    chatFrame.appendMessage(new Message(currentUser, message).toString());
                }
            }
        });
        chatFrame.setVisible(true);
    }
}